package com.pingan.generator.api.service.base;


import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import javax.persistence.Id;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pingan.generator.api.entity.base.BaseMapper;
import com.pingan.generator.api.entity.Pager;

/**
 * 
 * @author ouyangenkun051
 *
 * @param <T>
 * @param <X>
 */

@SuppressWarnings("rawtypes")
public abstract class BaseServiceImpl<T,X extends BaseMapper> implements BaseService<T> {

//	 @Autowired
//	 private TokenRedis tokenRedis;

    public abstract X getMapper();

    @SuppressWarnings("unchecked")
	public PageInfo<T> pagedList(Pager pager) {
        PageHelper.startPage(pager.getPageNo()<1?1:pager.getPageNo(), pager.getPageSize()>1000?1000:pager.getPageSize());
        List<T> orders = getMapper().pagedList(pager.getParams());
        return new PageInfo<>(orders);
    }

    @SuppressWarnings("unchecked")
	public List<T> allPagedList(Map<String,Object> paramMap) {
        return getMapper().pagedList(paramMap);
    }

    @SuppressWarnings("unchecked")
	public int save(T entity,String id) {
        if(StringUtils.isBlank(id)){
            return  getMapper().insertSelective(entity);
        }
        return getMapper().updateByPrimaryKeySelective(entity);
    }
    
	@SuppressWarnings("unchecked")
	public int save(T entity) {
		Object id =getPrimarykeyValue(entity);
		boolean flag = true;
		if (id!=null) {
			//如果类型是字符串那么就需要判断是否微空字符串其余调用
			if(id instanceof String){
				if(StringUtils.isBlank(id.toString()))
					flag=false;
			}else{
				flag = false;
			}
		}
		if(flag){
			return getMapper().insertSelective(entity);
		}else{
			return getMapper().updateByPrimaryKeySelective(entity);
		}
		
	}

	private Object getPrimarykeyValue(T entity) {
		Field idField = null;
		Class cls = entity.getClass();
		Field[] fields = cls.getDeclaredFields();
		Object id = null;
		// Class<?> type = null;
		if (fields != null) {
			try {
				for (Field field : fields) {
					if (!field.isAccessible()) {
						field.setAccessible(true);
					}
					Id annon = field.getAnnotation(Id.class);
					if (annon != null) {
						idField = field;
						id = idField.get(entity);
						break;
					}
				}
				if (idField != null) {
					for (int i = 0; i < fields.length; i++) {
						Field field = fields[i];
						if (!field.isAccessible()) {
							field.setAccessible(true);
						}
						if (field.getName().equals("id")) {
							idField = field;
							id = idField.get(entity);
							break;
							// type =fields[i].getType();
						}
					}
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return id;
	}

	public int  save(T entity,String idKey,Class clz,HttpServletRequest request){
//        Map<String, Object> map = ConverUtil.bean2map(entity,clz);
//        if(map==null){
//            return 0;
//        }
//        String token = request.getHeader(AuthenticationInterceptor.ACCESS_TOKEN);
//        token = StringUtils.isBlank(token)?request.getParameter(AuthenticationInterceptor.ACCESS_TOKEN):token;
//        if(!StringUtils.isEmpty(token)){
//        	 UserInfoWithBLOBs userinfo=tokenRedis.getUserInfoByToken(token);
//             map.put("updateBy",userinfo.getId());
//             map.put("updateTime",new Date());
//             if(map.get(idKey)==null || StringUtils.isBlank(map.get(idKey).toString())){
//                 map.put("createTime",new Date());
//                 map.put("createBy",userinfo.getId());
//                 map.put(idKey, UUID.randomUUID().toString());
//               
//                 return getMapper().insertSelective(map);
//             }
//            return getMapper().updateByPrimaryKeySelective(map);
//        }
        return 0;
    }

    @Override
    public int deleteById(String id){
       return getMapper().deleteByPrimaryKey(id);
    }
    
    @Override
    public int deleteById(T entity){
    	Object id =getPrimarykeyValue(entity);
		boolean flag = true;
		if (id!=null) {
			//如果类型是字符串那么就需要判断是否微空字符串其余调用
			if(id instanceof String){
				if(StringUtils.isBlank(id.toString()))
					flag=false;
			}else{
				flag = false;
			}
		}
		if(!flag){
			 return getMapper().deleteByPrimaryKey(id);
		}else{
			return 0;
		}
      
    }
}